package org.mathcloud.math.core.scilab.operator.algebra;

import org.apache.log4j.Logger;
import org.mathcloud.math.core.common.operator.algebra.Times;
import org.mathcloud.math.core.common.quantity.QuantityObject;
import org.mathcloud.math.core.common.signature.QuantityObjectSignature;
import org.mathcloud.math.core.scilab.factory.ScilabQuantityObjectFactory;
import org.mathcloud.math.core.scilab.manager.ScilabSupervisor;
import org.mathcloud.math.core.scilab.operator.ScilabNaryOperator;
import org.mathcloud.math.core.scilab.quantity.ScilabQuantityObject;
import org.scilab.modules.javasci.JavasciException;
import org.scilab.modules.types.ScilabDouble;

public class ScilabTimes extends ScilabNaryOperator implements Times
{
	public ScilabTimes()
	{
		super();
		signature.setMMLContentTag("times");
	}
	
	@Override
	public QuantityObject calculate(QuantityObject operand1, QuantityObject operand2)
	{
		QuantityObjectSignature resSign = getResultSignature(operand1, operand2);
		if (resSign!=null)
    {
      String sciJob;
      String tmpVar = "tmp_"+ScilabSupervisor.getVarId();
			ScilabQuantityObject tOp1 = ScilabQuantityObjectFactory.getInstance(operand1);
			ScilabQuantityObject tOp2 = ScilabQuantityObjectFactory.getInstance(operand2);
			sciJob = tmpVar;
			sciJob = sciJob + "="+ tOp1.getVarName();
      sciJob = sciJob + "*";
      sciJob = sciJob + tOp2.getVarName();;
      sciJob +=";";  
      if (sciEngine.exec(sciJob))
      {
      	log.info(sciJob);
      	try
				{
      		ScilabDouble tRes = (ScilabDouble)sciEngine.get(tmpVar);
	      	QuantityObject out = ScilabQuantityObjectFactory.getInstance(tRes);
					sciJob = "clear "+tmpVar+";";
					log.info(sciJob);
					if (sciEngine.exec(sciJob))
						return out;
					else return null; 
				} catch (JavasciException e)
				{
					log.error(e);
					return null;
				}
      }
      else
      {
      	log.info("SciJob execution fail");
      	return null;
      }
    } else return null;    				
	}
	
	private static final Logger log = Logger.getLogger(ScilabTimes.class);	
}
